package william.dp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ZhangShenao
 * @date 2024/3/28
 * @description <a href="https://leetcode.cn/problems/pascals-triangle/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 */
public class Leetcode118_杨辉三角 {
    /**
     * 采用动态规划实现
     * 自顶向下,对每一层逐个生成元素
     * <p>
     * 时间复杂度O(N^N)
     * 空间复杂度O(1)
     */
    public List<List<Integer>> generate(int numRows) {
        //边界条件校验
        if (numRows <= 0) {
            return Collections.emptyList();
        }

        List<List<Integer>> result = new ArrayList<>();

        //采用动态规划,自顶向下,对每一层逐个生成元素
        for (int i = 0; i < numRows; i++) {
            List<Integer> level = new ArrayList<>();
            for (int j = 0; j <= i; j++) {
                if (i == 0 || j == 0 || j == i) {
                    level.add(1);
                } else {
                    int v = result.get(i - 1).get(j - 1) + result.get(i - 1).get(j);
                    level.add(v);
                }
            }

            //保存当前层元素
            result.add(level);
        }

        //返回结果
        return result;
    }
}
